package org.zachary.creditbusiness.hotel.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.zachary.creditbusiness.hotel.service.OccupancyService;
import org.zachary.creditbusiness.hotel.util.ExecPythonProcess;

import java.io.IOException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@Service
public class OccupancyServiceImpl implements OccupancyService {

    private final ObjectMapper mapper = new ObjectMapper();
    private final String pythonExe  = "python";
    private final String scriptLoc = "pythonScripts/getHotelRate.py";
    private final String dataLoc   = "static/hoteldata";

    @Override
    public Map<String, Double> predict(Integer hotelId) {
        try {
            String scriptPath   = new ClassPathResource(scriptLoc).getFile().getAbsolutePath();
            String hotelDataDir = new ClassPathResource(dataLoc).getFile().getAbsolutePath();

            String dateStr = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"))
                    .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);

            String json = ExecPythonProcess.execPython(
                    pythonExe,
                    scriptPath,
                    hotelId.toString(),
                    dateStr,
                    hotelDataDir
            );

            return mapper.readValue(json, new TypeReference<Map<String,Double>>(){});
        } catch (IOException e) {
            throw new RuntimeException("入住率预测失败", e);
        }
    }
}